package cn.jbolt.ai.core.docParse;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.jbolt.util.QiniuUtil;
import cn.jbolt.util.Result;
import com.jboltai.capability.text.JBoltText;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DocParseServiceImpl implements DocParseService {
    private static final Logger logger = LoggerFactory.getLogger(DocParseServiceImpl.class);

    private final QiniuUtil qiniuUtil;

    @Autowired
    public DocParseServiceImpl(QiniuUtil qiniuUtil) {
        this.qiniuUtil = qiniuUtil;
    }

    @Override
    public Result docParse(String url) {
        if (StrUtil.isBlankIfStr(url)) {
            return Result.error("请输入要提取的文档地址");
        }
        try {
            com.jboltai.event.text.TextExtractEvent textExtractEvent =
                    JBoltText.extract(url).setId(RandomUtil.randomString(12)).setStream(false)
                            .onFile((event, fileInfo) -> {
                                try {
                                    String fileName = fileInfo.getFileName();
                                    Result<String> result = qiniuUtil.uploadFile(fileInfo.getInputStream(), fileName,null);
                                    String path = result.getData();
                                    logger.info("文档提取,图片上传成功, 图片地址: {}", path);
                                    return "![" + fileName + "](" + path + ")";
                                } catch (Exception e) {
                                    logger.error("文档提取,图片上传失败, 图片文件名: {}, 失败原因: {}", fileInfo.getFileName(), e.getMessage());
                                    return null;
                                }
                            });
            textExtractEvent.publish().await();
            if (textExtractEvent.isFail()) {
                logger.error("文档提取失败,文档地址为:{},失败原因:{}", url, textExtractEvent.getError().getMsg());
                return Result.error(textExtractEvent.getError().getMsg());
            } else {
                String content = textExtractEvent.getResult().getContent();
                logger.info("文档提取的内容{}:", content);
                return Result.success(content);
            }
        } catch (Exception e) {
            logger.error("文档提取失败,文档地址为:{},失败原因:{}", url, e.getMessage());
            return Result.error(e.getMessage());
        }
    }
}
